import Vue from 'vue'
import {createI18n} from 'vue-i18n'
import enLocale from 'element-plus/lib/locale/lang/en'
import zhLocale from 'element-plus/lib/locale/lang/zh-cn'
import tools from './tools'

// 获取当前locals文件夹下json
let loadLocaleMessages = (function () {
    const locales = require.context('../locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
    const messages = {}
    locales.keys().forEach(key => {
        const matched = key.match(/([A-Za-z0-9-_]+)\./i)
        if (matched && matched.length > 1) {
            const locale = matched[1]
            messages[locale] = locales(key)
        }
    })
    return messages
})()

// 融合loadLocaleMessages和ElementUI的语言包,加上loc前缀，避免与element冲突
let localeMessages = {
    'en-US': {
        loc: loadLocaleMessages['en-US'],
        ...enLocale
    },
    'zh-CN': {
        loc: loadLocaleMessages['zh-CN'],
        ...zhLocale
    },
}

// 默认保存的语言
let language = process.env.VUE_APP_I18N_LOCALE
// 失效时的默认语言
let FALLBACK_LOCALE = process.env.VUE_APP_I18N_FALLBACK_LOCALE

// 初始化VueI18n
const i18n = createI18n({
    locale: language || 'zh-CN',
    fallbackLocale: FALLBACK_LOCALE || 'zh-CN',
    globalInjection: true,
    messages: localeMessages,
})
// 暴露接口设置语言
export const setLocale = lang => {
    if (lang === undefined) {
        // 初始化获取 localStorage
        lang = tools.localItem('NG_TRANSLATE_LANG_KEY')
        // 设置无效语言时，返回默认 zh-CN
        if (localeMessages[lang] === undefined) {
            lang = language
        }
    }
    tools.localItem('NG_TRANSLATE_LANG_KEY', lang)
    Object.keys(localeMessages).forEach(lang => {
        document.getElementsByTagName('html')[0].classList.remove(`lang-${lang}`)
    })
    document.getElementsByTagName('html')[0].classList.add(`lang-${lang}`)
    document.getElementsByTagName('html')[0].setAttribute('lang', lang)
    i18n.locale = lang
}

// 初始化调用
setLocale()
// 当想要在非Vue的应用中调用时，通过i18n.global.t
window.$i18n = i18n

export default i18n
